//window resize events
$(window).resize(function() {
	//get the window size
	var wsize =  $(window).width();
	if (wsize > 980 ) {
		$('.shortcuts.hided').removeClass('hided').attr("style","");
		$('.sidenav.hided').removeClass('hided').attr("style","");
	}

	var size ="Window size is:" + $(window).width();
	/*console.log(size)*/
});

// document ready function
$(document).ready(function() { 	

	//prevent font flickering in some browsers 
	(function(){
	  //if firefox 3.5+, hide content till load (or 3 seconds) to prevent FOUT
	  var d = document, e = d.documentElement, s = d.createElement('style');
	  if (e.style.MozTransform === ''){ // gecko 1.9.1 inference
	    s.textContent = 'body{visibility:hidden}';
	    e.firstChild.appendChild(s);
	    function f(){ s.parentNode && s.parentNode.removeChild(s); }
	    addEventListener('load',f,false);
	    setTimeout(f,3000); 
	  }
	})();
	
  	//Disable certain links
    $('a[href^=#]').click(function (e) {
      e.preventDefault()
    })

    $('.search-btn,.no-uniform input,.no-uniform select').addClass('nostyle');//tell uniform to not style this element

    //Simple solution for this bug https://github.com/twitter/bootstrap/issues/4497
    $('body')
    .off('click.dropdown touchstart.dropdown.data-api', '.dropdown')
    .on('click.dropdown touchstart.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })


    //------------- Navigation -------------//

    mainNav = $('.mainnav>ul>li');
    mainNav.find('ul').siblings().addClass('hasUl').append('<span class="hasDrop icon16 icomoon-icon-arrow-down-2"></span>');
    mainNavLink = mainNav.find('a').not('.sub a');
    mainNavLinkAll = mainNav.find('a');
    mainNavSubLink = mainNav.find('.sub a').not('.sub li .sub a');
    mainNavCurrent = mainNav.find('a.current');

    /*Auto current system in main navigation */
    var domain = document.domain;
    var absoluteUrl = 0; //put value of 1 if use absolute path links. example http://www.host.com/dashboard instead of /dashboard

    function setCurrentClass(mainNavLinkAll, url) {
        mainNavLinkAll.each(function(index) {
            //convert href to array and get last element
            var href= $(this).attr('href');

            if(href == url) {
                //set new current class
                $(this).addClass('current');

                ulElem = $(this).parents('ul');  // Edited : closest() --> parents()
                if(ulElem.hasClass('sub')) {
                    //its a part of sub menu need to expand this menu
                    aElem = ulElem.prev('a.hasUl').addClass('drop');
                    ulElem.addClass('expand');
                }
            }
        });
    }


    if(domain === '') {
        //domain not found
        var pageUrl = window.location.pathname.split( '/' );
        var winLoc = pageUrl.pop(); // get last item

        setCurrentClass(mainNavLinkAll, winLoc);

    } else {
        if(absoluteUrl === 0) {
            //absolute url is disabled
            var afterDomain = window.location.pathname;

            setCurrentClass(mainNavLinkAll, afterDomain);

        } else {
            //absolute url is enabled
            var newDomain = 'http://' + domain + window.location.pathname;

            setCurrentClass(mainNavLinkAll, newDomain);
        }
    }

    //hover magic add blue color to icons when hover - remove or change the class if not you like.
    mainNavLinkAll.hover(
        function () {
            $(this).find('span.icon16').addClass('blue');
        },
        function () {
            $(this).find('span.icon16').removeClass('blue');
        }
    );

    //click magic
    mainNavLink.click(function(event) {
        $this = $(this);
        console.log($this)
        if($this.hasClass('hasUl')) {
            event.preventDefault();
            if($this.hasClass('drop')) {
                $(this).siblings('ul.sub').slideUp(500).siblings().removeClass('drop');
            } else {
                $(this).siblings('ul.sub').slideDown(500).siblings().addClass('drop');
            }
        }
    });
    mainNavSubLink.click(function(event) {
        $this = $(this);

        if($this.hasClass('hasUl')) {
            event.preventDefault();
            if($this.hasClass('drop')) {
                $(this).siblings('ul.sub').slideUp(500).siblings().removeClass('drop');
            } else {
                $(this).siblings('ul.sub').slideDown(250).siblings().addClass('drop');
            }
        }
    });

    //responsive buttons
    $('.resBtn>a').click(function(event) {
        $this = $(this);
        if($this.hasClass('drop')) {

            $('#header').css({'overflow-x': 'visible', 'width' : 'auto'});
            $('#header').animate({ 'margin-left' : '0'}, 300, function() {});
            $('#content').css({'overflow-x': 'visible', 'width' : 'auto'});
            $('#content').animate({ 'margin-left' : '0'}, 300, function() {});

            $('#sidebar>.shortcuts').slideUp(200).addClass('hided');
            $('#sidebar>.sidenav').slideUp(200).addClass('hided');
            $('#sidebar>.sidebar-widget').slideUp(200);

            $('#sidebar-right>.shortcuts').slideUp(200).addClass('hided');
            $('#sidebar-right>.sidenav').slideUp(200).addClass('hided');
            $('#sidebar-right>.sidebar-widget').slideUp(200);

            $('#sidebarbg').css('display', 'none');
            $('.resBtn').removeClass('offCanvas');

            $this.removeClass('drop');
        } else {
            if($('#sidebar').length) {
                $('#sidebar').css('display', 'block');
                if($('#sidebar-right').length) {
                    $('#sidebar-right').css({'display' : 'block', 'margin-top' : '0'});
                }
            }
            if($('#sidebar-right').length) {
                $('#sidebar-right').css('display', 'block');
            }

            $('#header').css({'overflow-x': 'hidden', 'width' : '100%'});
            $('#header').animate({ 'margin-left' : '211px'}, 300, function() {});
            $('#content').css({'overflow-x': 'hidden', 'width' : '100%'});
            $('#content').animate({ 'margin-left' : '211px'}, 300, function() {});

            $('#sidebar>.shortcuts').slideDown(250);
            $('#sidebar>.sidenav').slideDown(250);
            $('#sidebar>.sidebar-widget').slideDown(250);

            $('#sidebar-right>.shortcuts').slideDown(250);
            $('#sidebar-right>.sidenav').slideDown(250);
            $('#sidebar-right>.sidebar-widget').slideDown(250);

            $('#sidebarbg').css('display', 'block');
            $('.resBtn').addClass('offCanvas');

            $this.addClass('drop');
        }
    });

    $('.resBtnSearch>a').click(function(event) {
        $this = $(this);
        if($this.hasClass('drop')) {
            $('.search').slideUp(500);
            $this.removeClass('drop');
        } else {
            $('.search').slideDown(250);
            $this.addClass('drop');
        }
    });

    //Hide and show sidebar btn

    $(function () {
        //var pages = ['grid.html','charts.html'];
        var pages = [];

        for ( var i = 0, j = pages.length; i < j; i++ ) {

            if($.cookie("currentPage") == pages[i]) {
                var cBtn = $('.collapseBtn.leftbar');
                cBtn.children('a').attr('title','Show Left Sidebar');
                cBtn.addClass('shadow hide');
                cBtn.css({'top': '20px', 'left':'200px'});
                $('#sidebarbg').css('margin-left','-299'+'px');
                $('#sidebar').css('margin-left','-299'+'px');
                if($('#content').length) {
                    $('#content').css('margin-left', '0');
                }
                if($('#content-two').length) {
                    $('#content-two').css('margin-left', '0');
                }
            }

        }

    });

    $( '.collapseBtn' ).bind( 'click', function(){
        $this = $(this);

        //left sidbar clicked
        if ($this.hasClass('leftbar')) {

            if($(this).hasClass('hide')) {
                //show sidebar
                $('#sidebarbg').css('margin-left','0');
                $('#content').css('margin-left', '213'+'px');
                $('#content-two').css('margin-left', '213'+'px');
                $('#sidebar').css({'left' : '0', 'margin-left' : '0'});

                $this.removeClass('hide');
                $('.collapseBtn.leftbar').css('top', '168'+'px').css('left', '170'+'px').removeClass('shadow');
                $this.children('a').attr('title','Hide Left Sidebar');

            } else {
                //hide sidebar
                $('#sidebarbg').css('margin-left','-299'+'px');
                $('#sidebar').css('margin-left','-299'+'px');
                $('.collapseBtn.leftbar').animate({ //use .hide() if you experience heavy animation :)
                    left: '200',
                    top: '20'
                }, 500, 'easeInExpo', function() {
                    // Animation complete.

                }).addClass('shadow');
                //expand content
                $this.addClass('hide');
                $this.children('a').attr('title','Show Left Sidebar');
                if($('#content').length) {
                    $('#content').css('margin-left', '0');
                }
                if($('#content-two').length) {
                    $('#content-two').css('margin-left', '0');
                }

            }

        }

        //right sidebar clicked
        if ($this.hasClass('rightbar')) {

            if($(this).hasClass('hide')) {
                //show sidebar
                $('#sidebarbg-right').css('margin-right','0');
                $('#sidebar-right').css({'right' : '0', 'margin-right' : '0'});
                if($('#content').length) {
                    $('#content').css('margin-left', '213'+'px');
                }
                if($('#content-one').length) {
                    $('#content-one').css('margin-right', '212'+'px');
                }
                if($('#content-two').length) {
                    $('#content-two').css({'margin-right' : '212' + 'px'});
                }
                /*if($('#sidebar').length) {
                 $('#sidebar').css({'left' : '0', 'margin-left' : '0'});
                 }*/
                $this.removeClass('hide');
                $('.collapseBtn.rightbar').css('top', '120'+'px').css('right', '18'+'px').removeClass('shadow');
                $this.children('a').attr('title','Hide Right Sidebar');

            } else {
                //hide sidebar
                $('#sidebarbg-right').css('margin-right','-299'+'px');
                $('#sidebar-right').css('margin-right','-299'+'px');
                if($('#content').length) {
                    $('#content').css('margin-right', '0');
                }
                if($('#content-one').length) {
                    $('#content-one').css({'margin-left': '0', 'margin-right' : '0'});
                }
                if($('#content-two').length) {
                    $('#content-two').css({'margin-right' : '0'});
                }
                $('.collapseBtn.rightbar').animate({ //use .hide() if you experience heavy animation :)
                    right: '10',
                    top: '78'
                }, 500, 'easeInExpo', function() {
                    // Animation complete.

                }).addClass('shadow');
                //expand content
                $this.addClass('hide');
                $this.children('a').attr('title','Show Right Sidebar')
            }

        }
    });


	//------------- widget box magic -------------//

	var widget = $('div.box');
	var widgetOpen = $('div.box').not('div.box.closed');
	var widgetClose = $('div.box.closed');
	//close all widgets with class "closed"
	widgetClose.find('div.content').hide();
	widgetClose.find('.title>.minimize').removeClass('minimize').addClass('maximize');

	widget.find('.title>a').click(function (event) {
		event.preventDefault();
		var $this = $(this);
		if($this .hasClass('minimize')) {
			//minimize content
			$this.removeClass('minimize').addClass('maximize');
			$this.parent('div').addClass('min');
			cont = $this.parent('div').next('div.content')
			cont.slideUp(500, 'easeOutExpo'); //change effect if you want :)
			
		} else  
		if($this .hasClass('maximize')) {
			//minimize content
			$this.removeClass('maximize').addClass('minimize');
			$this.parent('div').removeClass('min');
			cont = $this.parent('div').next('div.content');
			cont.slideDown(500, 'easeInExpo'); //change effect if you want :)
		} 
		
	})

	//show minimize and maximize icons
	widget.hover(function() {
		    $(this).find('.title>a').show(50);	
		}
		, function(){
			$(this).find('.title>a').hide();	
	});

	//add shadow if hover box
	widget.hover(function() {
		    $(this).addClass('hover');	
		}
		, function(){
			$(this).removeClass('hover');	
	});


	//------------- Tooltips -------------//

	//top tooltip
	$('.tip').qtip({
		content: false,
		position: {
			my: 'bottom center',
			at: 'top center',
			viewport: $(window)
		},
		style: {
			classes: 'ui-tooltip-tipsy'
		}
	});

	//tooltip in right
	$('.tipR').qtip({
		content: false,
		position: {
			my: 'left center',
			at: 'right center',
			viewport: $(window)
		},
		style: {
			classes: 'ui-tooltip-tipsy'
		}
	});

	//tooltip in bottom
	$('.tipB').qtip({
		content: false,
		position: {
			my: 'top center',
			at: 'bottom center',
			viewport: $(window)
		},
		style: {
			classes: 'ui-tooltip-tipsy'
		}
	});

	//tooltip in left
	$('.tipL').qtip({
		content: false,
		position: {
			my: 'right center',
			at: 'left center',
			viewport: $(window)
		},
		style: {
			classes: 'ui-tooltip-tipsy'
		}
	});

	//--------------- Boostrap tooltips ------------------//
    $('.btip').tooltip();

	/* initialize the external events
	-----------------------------------------------------------------*/
	
	$('#external-events div.external-event').each(function() {
	
		// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
		// it doesn't need to have a start or end
		var eventObject = {
			title: $.trim($(this).text()) // use the element's text as the event title
		};
		
		// store the Event Object in the DOM element so we can get to it later
		$(this).data('eventObject', eventObject);
		
		// make the event draggable using jQuery UI
		$(this).draggable({
			zIndex: 999,
			revert: true,      // will cause the event to go back to its
			revertDuration: 0  //  original position after the drag
		});
		
	});

	//------------- Check all checkboxes  -------------//
	
	$("#masterCh").click(function() {
		var checkedStatus = $(this).find('span').hasClass('checked');
		$("#checkAll tr .chChildren input:checkbox").each(function() {
			this.checked = checkedStatus;
				if (checkedStatus == this.checked) {
					$(this).closest('.checker > span').removeClass('checked');
				}
				if (this.checked) {
					$(this).closest('.checker > span').addClass('checked');
				}
		});
	});
    //--------------- Tabs ------------------//
    $('#myTab a').click(function (e) {
	  	e.preventDefault();
	  	$(this).tab('show');
	})
    //activate loaders tabs
	$('#myTabLoaders a').click(function (e) {
	  	e.preventDefault();
	  	$(this).tab('show');
	})

    //make 2 tab active ( remove if not want )
	$('.tabs-right li:eq(1) a').tab('show'); // Select third tab (0-indexed)
	$('.tabs-left li:eq(1) a').tab('show'); // Select third tab (0-indexed)

	$('#loadersTab a').click(function (e) {
	  e.preventDefault();
	  $(this).tab('show');
	})

    //--------------- Accordion ------------------//
    var acc = $('.accordion'); //get all accordions
    var accHeading = acc.find('.accordion-heading');
	var accBody = acc.find('.accordion-body');

	//function to put icons
	accPutIcon = function () {
		acc.each(function(index) {
		   accExp = $(this).find('.accordion-body.in');
		   accExp.prev().find('a.accordion-toggle').append($('<span class="icon12 entypo-icon-minus-2 gray"></span>'));

		   accNor = $(this).find('.accordion-body').not('.accordion-body.in');
		   accNor.prev().find('a.accordion-toggle').append($('<span class="icon12 entypo-icon-plus-2 gray"></span>'));


		});
	}

	//function to update icons
	accUpdIcon = function() {
		acc.each(function(index) {
		   accExp = $(this).find('.accordion-body.in');
		   accExp.prev().find('span').remove();
		   accExp.prev().find('a.accordion-toggle').append($('<span class="icon12 entypo-icon-minus-2 gray"></span>'));

		   accNor = $(this).find('.accordion-body').not('.accordion-body.in');
		   accNor.prev().find('span').remove();
		   accNor.prev().find('a.accordion-toggle').append($('<span class="icon12 entypo-icon-plus-2 gray"></span>'));


		});
	}

	accPutIcon();

	$('.accordion').on('shown', function () {
		accUpdIcon();
	}).on('hidden', function () {
		accUpdIcon();
	})

	//--------------- Sliders ------------------//
	//simple slider
	$( "#slider" ).slider(); 
	//with 50 range
	$( "#slider1" ).slider({
		range: "min",
		value:100,
		min: 1,
		max: 500,
		step: 50,
		slide: function( event, ui ) {
			$( "#amount" ).val( "$" + ui.value );
		}
	});
	$( "#amount" ).val( "$" + $( "#slider" ).slider( "value" ) );
	//range slider
	$( "#slider-range" ).slider({
		range: true,
		min: 0,
		max: 500,
		values: [ 75, 300 ],
		slide: function( event, ui ) {
			$( "#amount1" ).val( "Price range: $" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
		}
	});
	$( "#amount1" ).val( "Price range: $" + $( "#slider-range" ).slider( "values", 0 ) +
		" - $" + $( "#slider-range" ).slider( "values", 1 ) );

	//with minimum
	$( "#slider-range-min" ).slider({
		range: "min",
		value: 37,
		min: 1,
		max: 700,
		slide: function( event, ui ) {
			$( "#amount2" ).val( "Maximum price: $" + ui.value );
		}
	});
	$( "#amount2" ).val( "Maximum price: $" + $( "#slider-range-min" ).slider( "value" ) );
	//with maximum
	$( "#slider-range-max" ).slider({
		range: "max",
		min: 1,
		max: 10,
		value: 2,
		slide: function( event, ui ) {
			$( "#amount3" ).val("Minimum number of bedrooms:" + ui.value );
		}
	});
	$( "#amount3" ).val( "Minimum number of bedrooms:" + $( "#slider-range-max" ).slider( "value" ) );

	//vertical sliders
	$( "#eq > span" ).each(function() {
		// read initial values from markup and remove that
		var value = parseInt( $( this ).text(), 10 );
		$( this ).empty().slider({
			value: value,
			range: "min",
			animate: true,
			orientation: "vertical"
		});
	});

    //--------------- Dialogs ------------------//
	$('#openDialog').click(function(){
		$('#dialog').dialog('open');
		return false;
	});

	$('#openModalDialog').click(function(){
		$('#modal').dialog('open');
		return false;
	});

	// JQuery Dialog			
	$('#dialog').dialog({
		autoOpen: false,
		dialogClass: 'dialog',
		buttons: {
			"Close": function() { 
				$(this).dialog("close"); 
			}
		}
	});

	// JQuery UI Modal Dialog			
	$('#modal').dialog({
		autoOpen: false,
		modal: true,
		dialogClass: 'dialog',
		buttons: {
			"Close": function() { 
				$(this).dialog("close"); 
			}
		}
	});

	$("div.dialog button").addClass("btn");

	//Boostrap modal
	$('#myModal').modal({ show: false});
	//add event to modal after closed
	$('#myModal').on('hidden', function () {
	  	$.pnotify({
		    title: 'Modal',
		    text: 'Modal window is closed',
		    icon: 'picon icon16 entypo-icon-warning white',
		    opacity: 0.95,
		    sticker: false,
		    history: false
		});
	})
    //------------- Elastic textarea -------------//
    if ($('textarea').hasClass('elastic')) {
        $('.elastic').elastic();
    }
    //------------- Uniform  -------------//
    //add class .nostyle if not want uniform to style field
    $(".filters select").addClass('nostyle');
    $("input, textarea, select").not('.nostyle').uniform();
	//remove loadstate class from body and show the page
	setTimeout('$("html").removeClass("loadstate")',300);

});
   //---------------Fix tooltip after ajax call --------//
    $(document).on('mouseenter','[rel=tooltip]', function(){
        $(this).tooltip('show');
    });

    $(document).on('mouseleave','[rel=tooltip]', function(){
        $(this).tooltip('hide');
    });

function callAjax(url,type,data,update,cf)
{
    if(cf) {
        bootbox.confirm(cf, function(result) {
            if(result) {
                jQuery.ajax({
                    'type':type,
                    'data':data,
                    'beforeSend':function(){
                        $(update).empty();
                        $(update).addClass('grid-view-loading');
                    },
                    'complete':function(){
                        $(update).removeClass('grid-view-loading');
                    },
                    'url':url,
                    'cache':false,
                    'success':function(html){
                        jQuery(update).html(html);
                    }
                });
            } else {
                return false;
            }
        });
    }

    return false;
}

function changeStatus(url,data,update,cf)
{
    if(cf) {
        bootbox.confirm(cf, function(result) {
            if(result) {
                jQuery.ajax({
                    'type':'POST',
                    'data':data,
                    'dataType':'json',
                    'beforeSend':function(){
                        $(update).empty();
                        $(update).addClass('grid-view-loading');
                    },
                    'complete':function(){
                        $(update).removeClass('grid-view-loading');
                    },
                    'url':url,
                    'cache':false,
                    'success':function(string){
                        $.each(string, function (index,item){
                            var icon = 'icon-remove';
                            if(item.status == 1) {
                                icon = 'icon-ok';
                            }
                            $(item.idhtml).html('<a onclick="changeStatus(\''+item.url+'\','+item.token+',\''+item.idhtml+'\',\''+item.mes+'\');return false" rel="'+item.rel+'" data-original-title="'+item.tooltipTitle+'" href="'+item.url+'"><span class="'+icon+'"></span></a>');
                        });

                    }
                });
            } else {
                return false;
            }
        });
    }
    return false;
}